<template>
	<view class="resource-calendar">
		<!-- 日历和资源列表区域 -->
		<view class="calendar-container">
			<!-- 月份导航 -->
			<view class="month-navigation">
				<view class="nav-btn" @click="prevMonth">
					<text class="nav-arrow">‹</text>
				</view>
				<picker mode="date" fields="month" @change="changeMonth">
					<text class="date-picker">{{currentMonth}}</text>
				</picker>
				<view class="nav-btn" @click="nextMonth">
					<text class="nav-arrow">›</text>
				</view>
			</view>

			<!-- 简化版日历显示 -->
			<view class="simple-calendar" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
				<view class="calendar-header">
					<text class="weekday" v-for="day in weekDays" :key="day">{{day}}</text>
				</view>
				<view class="calendar-body">
					<view class="calendar-cell" v-for="day in calendarDays" :key="day.date" :class="{
                  'other-month': !day.currentMonth,
                  'current-day': day.isToday,
                  'selected-day': day.isSelected,
                  'has-event': day.hasEvent
                }" @click="!isSwiping && selectDate(day.date)">
						<text class="day-number">{{day.day}}</text>
						<view class="event-dot" v-if="day.hasEvent"
							:style="{backgroundColor: day.isImportant ? '#FF3B30' : '#007AFF'}"></view>
					</view>
				</view>
			</view>


		</view>

		<!-- 团信息展示模块 -->
		<view class="group-info-container">
			<view class="group-info-header">
				<text class="group-info-title">团信息 - {{ formatDate(selectedDate) }}</text>
				<image class="action-icon" src="/static/icons/help.png" mode="aspectFit"
					@click.stop="showOrderHelpModal = true"></image>
			</view>
			<view class="group-list" v-if="selectedDateGroups && selectedDateGroups.length > 0">
				<view class="group-item" v-for="(group, index) in selectedDateGroups" :key="index">
					<view class="group-item-header">
						<text class="group-name"
							:style="{color: groupColors[group.groupName] || '#333'}">{{ group.groupName || '未命名团' }} -
							{{ group.groupCode }} - {{ this.getStatusText(group.status) }} <text class="info-value"
								style="color: #007AFF; cursor: pointer;" @click="viewTourGroupDetail(group.id)">
								查看详情→</text>
						</text>
					</view>
					<view class="group-item-body horizontal-layout">
						<view class="group-info-item">
							<text class="info-label">人数/实际人数</text>
							<view class="info-container">
								<text class="info-value">{{ group.capacity || 0 }}人/{{ group.groupSize || 0 }}人</text>
							</view>
						</view>

						<!-- 导游信息展示 -->
						<view class="group-info-item" :class="{ 'unassigned': !group.guideName }">
							<view style="display: flex; justify-content: center;">
								<text class="info-label">导游</text>
								<image v-if="group.guideName" src="/static/icons/replace.png" class="replace-icon"
									mode="aspectFit" @click="openGuideDrawer(group)" :style="{ cursor: 'pointer' }">
								</image>
							</view>
							<view class="info-container">
								<text v-if="group.guideName" class="info-value">
									{{ group.guideName }}
								</text>
								<view v-else class="empty-placeholder" @click="openGuideDrawer(group)">
									<text class="plus-sign">＋</text>
								</view>
							</view>
						</view>

						<!-- 车辆信息展示 -->
						<view class="group-info-item" :class="{ 'unassigned': !group.vehicleLicensePlate }">
							<view style="display: flex; justify-content: center;">
								<text class="info-label">车辆</text>
								<image v-if="group.vehicleLicensePlate" src="/static/icons/replace.png"
									class="replace-icon" mode="aspectFit" @click="openVehicleDrawer(group)"
									:style="{ cursor: 'pointer' }"></image>
							</view>
							<view class="info-container">
								<text v-if="group.vehicleLicensePlate" class="info-value">
									{{ group.driverName ? group.driverName + ' - ' : '' }}{{ group.vehicleLicensePlate }}
								</text>
								<view v-else class="empty-placeholder" @click="openVehicleDrawer(group)">
									<text class="plus-sign">＋</text>
								</view>
							</view>
						</view>

						<view class="group-info-item">
							<text class="info-label">行程:{{ group.itineraryName || '未指定' }}</text>
							<view class="info-container">
								<text class="info-value"></text>
							</view>
						</view>


					</view>
				</view>
			</view>
			<view class="empty-group" v-else>
				<text class="empty-text">该日期暂无团信息</text>
			</view>
		</view>

		<!-- 导游选择抽屉 -->
		<view class="drawer guide-drawer flat-drawer" :class="{ show: showGuideDrawer }" @touchmove.stop>
			<view class="drawer-header flat-drawer-header">
				<text class="drawer-title">选择导游</text>
				<image src="/static/icons/close.png" class="drawer-close" mode="aspectFit" @click="closeGuideDrawer" />
			</view>
			<view class="drawer-search">
				<input class="search-input" v-model="guideSearchText" placeholder="搜索导游名称" />
			</view>
			<view class="drawer-body flat-drawer-body">
				<view v-if="loadingGuidesAndVehicles" class="loading-state">
					<text class="loading-text">加载中...</text>
				</view>
				<view v-else-if="filteredGuides.length > 0">
					<view v-for="(guide, idx) in filteredGuides" :key="idx" class="drawer-item flat-drawer-item"
						:class="{ active: selectedGroup?.guideId === filteredGuideIds[idx] }" @click="selectGuide(idx)">
						<text class="item-name">{{ guide }}</text>
						<image v-if="selectedGroup?.guideId === filteredGuideIds[idx]" src="/static/icons/selected.png"
							class="item-selected" mode="aspectFit" />
					</view>
				</view>
				<view v-else class="no-result">
					<text>未找到匹配的导游</text>
				</view>
			</view>
		</view>

		<!-- 车辆选择抽屉 -->
		<view class="drawer vehicle-drawer flat-drawer" :class="{ show: showVehicleDrawer }" @touchmove.stop>
			<view class="drawer-header flat-drawer-header">
				<text class="drawer-title">选择车辆</text>
				<image src="/static/icons/close.png" class="drawer-close" mode="aspectFit"
					@click="closeVehicleDrawer" />
			</view>
			<view class="drawer-search">
				<input class="search-input" v-model="vehicleSearchText" placeholder="搜索车辆信息" />
			</view>
			<view class="drawer-body flat-drawer-body">
				<view v-if="loadingGuidesAndVehicles" class="loading-state">
					<text class="loading-text">加载中...</text>
				</view>
				<view v-else-if="filteredVehicles.length > 0">
					<view v-for="(vehicle, idx) in filteredVehicles" :key="idx"
						class="drawer-item flat-drawer-item vehicle-item"
						:class="{ active: selectedGroup?.vehicleId === filteredVehicleIds[idx] }"
						@click="selectVehicle(idx)">
						<!-- 车辆信息容器 -->
						<view class="vehicle-content">
							<!-- 车辆主信息 - 一行展示 -->
							<view class="vehicle-main-info">
								<text class="vehicle-title">{{ vehicle }}</text>
							</view>
							<!-- 车辆详细信息（如果有） -->
							<view v-if="filteredVehicleDetails[idx] && filteredVehicleDetails[idx].licensePlate"
								class="vehicle-info-details">
								<text class="vehicle-detail-item">
									<text class="detail-label">车牌号:</text>
									<text
										class="detail-value">{{ filteredVehicleDetails[idx].licensePlate || '未提供' }}</text>
								</text>
								<text class="vehicle-detail-item">
									<text class="detail-label">司机:</text>
									<text
										class="detail-value">{{ filteredVehicleDetails[idx].driverName || '未指定' }}</text>
								</text>
								<text class="vehicle-detail-item">
									<text class="detail-label">电话:</text>
									<text
										class="detail-value">{{ filteredVehicleDetails[idx].driverPhone || '未提供' }}</text>
								</text>
								<!-- 显示载客量信息 -->
								<text v-if="filteredVehicleDetails[idx].loadCapacity" class="vehicle-detail-item">
									<text class="detail-label">载客量:</text>
									<text class="detail-value">{{ filteredVehicleDetails[idx].loadCapacity }}人</text>
								</text>
							</view>
						</view>
						<!-- 选中标记 -->
						<image v-if="selectedGroup?.vehicleId === filteredVehicleIds[idx]"
							src="/static/icons/selected.png" class="item-selected" mode="aspectFit" />
					</view>
				</view>
				<view v-else class="no-result">
					<text>未找到匹配的车辆</text>
				</view>
			</view>
		</view>

		<!-- 全局抽屉遮罩层 -->
		<view class="drawer-mask flat-mask" :class="{ show: showGuideDrawer || showVehicleDrawer }"
			@click="closeAllDrawers">
		</view>

		<!-- 操作说明弹窗 -->
		<view class="help-modal" v-if="showOrderHelpModal">
			<view class="help-modal-overlay" @click="showOrderHelpModal = false"></view>
			<view class="help-modal-content">
				<view class="help-modal-header">
					<text class="help-modal-title">操作说明</text>
				</view>
				<view class="help-modal-body">
					<!-- 日历标记说明 -->
					<view class="help-item">
						<view class="help-icon">
							<view style="width: 16rpx; height: 16rpx; background-color: #007AFF; border-radius: 50%;">
							</view>
						</view>
						<view class="help-text">
							<text class="help-title">蓝色标记</text>
							<text class="help-desc">表示该日期有团期安排</text>
						</view>
					</view>
					<view class="help-item">
						<view class="help-icon">
							<view style="width: 16rpx; height: 16rpx; background-color: #FF3B30; border-radius: 50%;">
							</view>
						</view>
						<view class="help-text">
							<text class="help-title">红色标记</text>
							<text class="help-desc">表示有未分配导游或车辆的数据</text>
						</view>
					</view>
					<view class="help-item">
						<view class="help-icon">
							<image src="/static/icons/replace.png" mode="aspectFit"
								style="width: 28rpx; height: 28rpx;"></image>
						</view>
						<view class="help-text">
							<text class="help-title">替换图标</text>
							<text class="help-desc">点击可以更换已绑定的数据</text>
						</view>
					</view>
					<view class="help-item">
						<view class="help-icon">
							<text style="font-size: 32rpx; color: #999;">＋</text>
						</view>
						<view class="help-text">
							<text class="help-title">加号标识</text>
							<text class="help-desc">点击可以绑定新的数据</text>
						</view>
					</view>
				</view>
				<view class="help-modal-footer">
					<button class="help-confirm-btn" @click="showOrderHelpModal = false">我知道了</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getDateGroupStatus,
		getTourGroupByDateRange,
		bindGuideToTourGroup,
		bindVehicleToTourGroup
	} from '../../https/tourgroup.js';
	import {
		GetSelectList as getGuideSelectList
	} from '../../https/guide.js';
	import {
		GetSelectList as getVehicleSelectList
	} from '../../https/vehicle.js';
	export default {
		components: {
			// uni-app内置组件无需显式注册，uni-popup会自动按需引入
		},
		data() {
			const today = new Date()
			const currentDateStr = today.toISOString().split('T')[0]

			return {
				currentDate: today,
				currentMonth: `${today.getFullYear()}年${today.getMonth()+1}月`,
				selectedDate: currentDateStr,
				weekDays: ['日', '一', '二', '三', '四', '五', '六'],
				calendarDays: [],
				// 触摸事件相关变量
				touchStartX: 0,
				touchEndX: 0,
				isSwiping: false,
				// 帮助弹窗控制变量
				showOrderHelpModal: false,

				// 新增团期数据
				dateGroupStatus: [],
				// 选中日期的团信息
				selectedDateGroups: [],
				// 当前openId
				openId: '', // 需要从本地存储或全局状态中获取
				// 资源数组 - 初始化空数组防止undefined错误
				resources: [],
				// 选中的团信息
				selectedGroup: null,

				// 导游选择相关
				showGuideDrawer: false,
				guides: [],
				guideIds: [],
				guideSearchText: '',

				// 车辆选择相关
				showVehicleDrawer: false,
				vehicles: [],
				vehicleIds: [],
				vehicleDetails: [],
				vehicleSearchText: '',

				// 加载状态
				loadingGuidesAndVehicles: false,
				submitting: false
			}
		},

		computed: {
			// 团队颜色映射 - 保留供日历显示使用
			groupColors() {
				return {
					'A团': '#4CD964',
					'B团': '#F0AD4E',
					'C团': '#DD524D',
					'D团': '#5AC8FA',
					'E团': '#FF9500',
					'F团': '#AF52DE'
				}
			},

			// 过滤后的导游列表
			filteredGuides() {
				if (!this.guideSearchText) return this.guides;
				return this.guides.filter(guide =>
					guide.toLowerCase().includes(this.guideSearchText.toLowerCase())
				);
			},

			// 过滤后的导游ID列表
			filteredGuideIds() {
				if (!this.guideSearchText) return this.guideIds;
				const searchText = this.guideSearchText.toLowerCase();
				return this.guides
					.map((guide, index) => ({
						guide,
						index
					}))
					.filter(item => item.guide.toLowerCase().includes(searchText))
					.map(item => this.guideIds[item.index]);
			},

			// 过滤后的车辆列表
			filteredVehicles() {
				if (!this.vehicleSearchText) return this.vehicles;
				return this.vehicles.filter(vehicle =>
					vehicle.toLowerCase().includes(this.vehicleSearchText.toLowerCase())
				);
			},

			// 过滤后的车辆ID列表
			filteredVehicleIds() {
				if (!this.vehicleSearchText) return this.vehicleIds;
				const searchText = this.vehicleSearchText.toLowerCase();
				return this.vehicles
					.map((vehicle, index) => ({
						vehicle,
						index
					}))
					.filter(item => item.vehicle.toLowerCase().includes(searchText))
					.map(item => this.vehicleIds[item.index]);
			},

			// 过滤后的车辆详情列表
			filteredVehicleDetails() {
				if (!this.vehicleSearchText) return this.vehicleDetails;
				const searchText = this.vehicleSearchText.toLowerCase();
				return this.vehicles
					.map((vehicle, index) => ({
						vehicle,
						index
					}))
					.filter(item => item.vehicle.toLowerCase().includes(searchText))
					.map(item => this.vehicleDetails[item.index]);
			}
		},

		onLoad() {
			// 使用uni-app生命周期钩子
			this.initData();
		},

		onShow() {
			// 如果有需要在页面显示时执行的逻辑
			if (this.selectedDateGroups.length > 0) {
				// 可以在这里重新加载导游和车辆列表
				// this.loadGuidesAndVehicles();
			}
		},

		methods: {
			// 初始化数据
			async initData() {
				try {
					// 获取openId（这里需要根据实际情况获取，比如从缓存或全局状态）
					this.openId = uni.getStorageSync('openId') || 'test_openid';

					// 初始化顺序优化
					this.initCalendar();
					await this.fetchDateGroupStatus();
				} catch (error) {
					console.error('初始化数据失败:', error);
					uni.showToast({
						title: '初始化失败',
						icon: 'none'
					});
				}
			},

			// 加载导游和车辆列表
			async loadGuidesAndVehicles(group = null) {
				console.log('开始加载导游和车辆列表');
				// 如果传入了团信息，则使用该团信息
				if (group) {
					this.selectedGroup = group;
				}

				// 显示加载状态
				this.loadingGuidesAndVehicles = true;

				try {
					// 构建导游参数 - 与addgroup.vue保持一致的格式
					const guideParams = {
						StartDate: this.selectedGroup.startDate,
						EndDate: this.selectedGroup.endDate,
						count: this.selectedGroup?.capacity || 0 // 使用团人数
					};
					console.log('导游参数:', guideParams);

					// 构建车辆参数
					const vehicleParams = {
						StartDate: this.selectedGroup.startDate,
						EndDate: this.selectedGroup.endDate,
						count: this.selectedGroup?.capacity || 0 // 使用团人数
					};

					// 并发请求导游和车辆列表
					const [guideList, vehicleList] = await Promise.all([
						getGuideSelectList(guideParams),
						getVehicleSelectList(vehicleParams)
					]);

					// 处理导游数据
					console.log('获取到的导游列表:', guideList);
					if (Array.isArray(guideList) && guideList.length > 0) {
						this.guides = guideList.map(item => item.Label || '未知导游');
						this.guideIds = guideList.map(item => item.Value || null);
					} else {
						console.warn('导游列表为空或格式不正确');
						this.guides = ['暂无可用导游'];
						this.guideIds = [null];
					}

					// 处理车辆数据
					if (Array.isArray(vehicleList) && vehicleList.length > 0) {
						console.log('获取到的车辆列表:', vehicleList);
						// 存储完整的车辆详情
						this.vehicleDetails = vehicleList;
						// 格式化显示的车辆文本
						this.vehicles = vehicleList.map(item => {
							if (item.Label) {
								return item.Label;
							} else if (item.licensePlate) {
								return `${item.licensePlate} - ${item.vehicleType || '未知车型'} - 核载${item.loadCapacity || 0}人`;
							}
							return '未知车辆';
						});
						// 提取车辆ID，优先使用vehicleId字段
						this.vehicleIds = vehicleList.map(item => {
							const vehicleId = item.vehicleId || item.Value;
							return vehicleId || null;
						});
					} else {
						console.warn('车辆列表为空或格式不正确');
						this.vehicles = ['暂无可用车辆'];
						this.vehicleIds = [null];
						this.vehicleDetails = [];
					}

				} catch (error) {
					console.error('加载导游和车辆失败:', error);
					uni.showToast({
						title: '加载导游和车辆列表失败，请重试',
						icon: 'none'
					});
					// 重置数据，避免显示错误信息
					this.guides = ['加载失败，请重试'];
					this.guideIds = [null];
					this.vehicles = ['加载失败，请重试'];
					this.vehicleIds = [null];
					this.vehicleDetails = [];
				} finally {
					// 隐藏加载状态
					this.loadingGuidesAndVehicles = false;
				}
			},

			// 打开导游选择抽屉
			openGuideDrawer(group) {
				this.selectedGroup = group;
				// 重置搜索文本
				this.guideSearchText = '';
				// 加载导游列表
				this.loadGuidesAndVehicles(group);
				// 显示抽屉
				this.showGuideDrawer = true;
			},

			// 关闭导游选择抽屉
			closeGuideDrawer() {
				this.showGuideDrawer = false;
				this.guideSearchText = '';
			},

			// 打开车辆选择抽屉
			openVehicleDrawer(group) {
				if (!group) return;

				// 保存当前选中的团信息
				this.selectedGroup = group;

				// 确保导游和车辆数据已加载
				if (!this.guides.length || !this.vehicles.length) {
					this.loadGuidesAndVehicles();
				}

				// 打开抽屉
				this.showVehicleDrawer = true;
			},

			// 关闭车辆抽屉
			closeVehicleDrawer() {
				this.showVehicleDrawer = false;
				this.vehicleSearchText = '';
			},

			// 查看团期详情
			viewTourGroupDetail(taskId) {
				uni.navigateTo({
					url: `/pages/groups/tourGroupDetail?groupId=${taskId}`
				});
			},

			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					0: '未开始',
					1: '进行中',
					2: '已结束'
				};
				return statusMap[status] || '未知';
			},

			// 选择车辆
			async selectVehicle(index) {
				if (this.submitting || this.loadingGuidesAndVehicles) return;

				const vehicleId = this.filteredVehicleIds[index];
				const vehicleName = this.filteredVehicles[index];
				const vehicleDetail = this.filteredVehicleDetails[index];

				console.log('选择车辆:', {
					vehicleId,
					vehicleName,
					vehicleDetail
				});

				// 确保有选中的团信息
				if (!this.selectedGroup || !this.selectedGroup.id) {
					uni.showToast({
						title: '团信息无效',
						icon: 'none'
					});
					return;
				}

				try {
					this.submitting = true;

					// 调用API绑定车辆
					const bindParams = {
						tourGroupId: this.selectedGroup.id,
						vehicleId: vehicleId
					};

					console.log('调用绑定车辆API参数:', bindParams);
					const result = await bindVehicleToTourGroup(bindParams);

					console.log('绑定车辆API返回结果:', result);

					// API调用成功后再更新本地数据
					this.selectedGroup.vehicleId = vehicleId;
					if (vehicleDetail) {
						// 更新为新的数据结构字段
						this.selectedGroup.vehicleLicensePlate = vehicleDetail.licensePlate || vehicleName;
						this.selectedGroup.vehicleType = vehicleDetail.vehicleType || '未知车型';
						this.selectedGroup.driverName = vehicleDetail.driverName || '未指定';
						this.selectedGroup.driverPhone = vehicleDetail.driverPhone || '';
					} else {
						this.selectedGroup.vehicleLicensePlate = vehicleName;
						this.selectedGroup.vehicleType = '未知车型';
					}

					// 显示成功提示
					uni.showToast({
						title: '车辆绑定成功',
						icon: 'success'
					});

				} catch (error) {
					console.error('绑定车辆失败:', error);
					uni.showToast({
						title: '绑定车辆失败，请重试',
						icon: 'none'
					});
				} finally {
					this.submitting = false;
				}

				// 关闭抽屉
				this.closeVehicleDrawer();
			},

			// 选择导游
			async selectGuide(index) {
				if (this.submitting || this.loadingGuidesAndVehicles) return;

				const guideId = this.filteredGuideIds[index];
				const guideName = this.filteredGuides[index];

				console.log('选择导游:', {
					guideId,
					guideName
				});

				// 确保有选中的团信息
				if (!this.selectedGroup || !this.selectedGroup.id) {
					uni.showToast({
						title: '团信息无效',
						icon: 'none'
					});
					return;
				}

				try {
					this.submitting = true;

					// 调用API绑定导游
					const bindParams = {
						tourGroupId: this.selectedGroup.id,
						guideId: guideId
					};

					console.log('调用绑定导游API参数:', bindParams);
					const result = await bindGuideToTourGroup(bindParams);

					console.log('绑定导游API返回结果:', result);

					// API调用成功后再更新本地数据
					this.selectedGroup.guideId = guideId;
					this.selectedGroup.guideName = guideName;

					// 显示成功提示
					uni.showToast({
						title: '导游绑定成功',
						icon: 'success'
					});

				} catch (error) {
					console.error('绑定导游失败:', error);
					uni.showToast({
						title: '绑定导游失败，请重试',
						icon: 'none'
					});
				} finally {
					this.submitting = false;
				}

				// 关闭抽屉
				this.closeGuideDrawer();
			},

			// 获取近期团期数据
			async fetchDateGroupStatus() {
				uni.showLoading({
					title: '加载中',
					mask: true
				});

				try {
					const res = await getDateGroupStatus({});

					if (res && Array.isArray(res)) {
						// 数据预处理：统一日期格式并过滤有效数据
						this.dateGroupStatus = res
							// 过滤掉ishave不为True的数据
							.filter(item => !item.ishave || item.ishave === true)
							// 转换日期格式
							.map(item => {
								// 处理对象格式，包含data字段的情况
								if (item && item.data) {
									// 创建新对象，保留原始字段但更新data格式
									return {
										...item,
										data: item.data.replace(/\//g, '-')
									};
								}
								// 处理字符串格式
								if (typeof item === 'string') {
									return item.replace(/\//g, '-');
								}
								return item;
							});
						// 更新日历显示
						this.initCalendar();
						
						// 检查今天的数据标志中ishave是否为真，如果是则自动查询今天的团信息
						const today = new Date().toISOString().split('T')[0];
						const todayData = this.dateGroupStatus.find(item => {
							if (typeof item === 'string') {
								return item === today;
							}
							if (item && (item.data || item.date)) {
								return (item.data || item.date) === today;
							}
							return false;
						});
						
						if (todayData && todayData.ishave === true) {
							await this.fetchTourGroupByDate(today);
						}
					}
				} catch (error) {
					console.error('获取近期团期失败:', error);
					uni.showToast({
						title: '加载团期数据失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			// 初始化日历数据
			initCalendar() {
				const year = this.currentDate.getFullYear()
				const month = this.currentDate.getMonth()

				// 获取当月第一天
				const firstDay = new Date(year, month, 1)
				// 获取当月最后一天
				const lastDay = new Date(year, month + 1, 0)
				// 获取当月第一天是星期几
				const firstDayWeek = firstDay.getDay()

				const days = []

				// 添加上个月的日期
				const prevMonthLastDay = new Date(year, month, 0).getDate()
				for (let i = firstDayWeek - 1; i >= 0; i--) {
					const dateStr =
						`${year}-${month.toString().padStart(2, '0')}-${(prevMonthLastDay - i).toString().padStart(2, '0')}`
					const eventInfo = this.checkDateHasEvent(dateStr)
					days.push({
						date: dateStr,
						day: prevMonthLastDay - i,
						currentMonth: false,
						isToday: false,
						isSelected: false,
						hasEvent: eventInfo.hasEvent,
						isImportant: eventInfo.isImportant
					})
				}

				// 添加当月的日期
				const today = new Date().toISOString().split('T')[0]
				for (let i = 1; i <= lastDay.getDate(); i++) {
					const dateStr = `${year}-${(month + 1).toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`
					const eventInfo = this.checkDateHasEvent(dateStr)
					days.push({
						date: dateStr,
						day: i,
						currentMonth: true,
						isToday: dateStr === today,
						isSelected: dateStr === this.selectedDate,
						hasEvent: eventInfo.hasEvent,
						isImportant: eventInfo.isImportant
					})
				}

				// 添加下个月的日期，补齐6行
				const remainingDays = 42 - days.length // 6行 x 7列 = 42
				for (let i = 1; i <= remainingDays; i++) {
					const dateStr = `${year}-${(month + 2).toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`
					const eventInfo = this.checkDateHasEvent(dateStr)
					days.push({
						date: dateStr,
						day: i,
						currentMonth: false,
						isToday: false,
						isSelected: false,
						hasEvent: eventInfo.hasEvent,
						isImportant: eventInfo.isImportant
					})
				}

				this.calendarDays = days
			},

			// 检查日期是否有事件（团期）并返回是否重要
			checkDateHasEvent(dateStr) {
				// 优先使用接口返回的团期数据
				if (this.dateGroupStatus && this.dateGroupStatus.length > 0) {
					const eventItem = this.dateGroupStatus.find(item => {
						// 处理字符串格式
						if (typeof item === 'string') {
							// 转换字符串日期格式（斜杠转横杠）进行比较
							const formattedItem = item.replace(/\//g, '-');
							return formattedItem === dateStr;
						}
						// 处理对象格式，支持data字段和date字段
						if (item) {
							// 处理data字段（斜杠格式转换为横杠格式）
							if (item.data) {
								const formattedData = item.data.replace(/\//g, '-');
								return formattedData === dateStr;
							}
							// 兼容date字段
							return item.date === dateStr;
						}
						return false;
					});

					// 如果找到事件，返回是否重要的信息
					if (eventItem && typeof eventItem === 'object') {
						return {
							hasEvent: true,
							isImportant: eventItem.important === true
						};
					}
					return {
						hasEvent: !!eventItem,
						isImportant: false
					};
				}
				// 兼容原有逻辑，添加resources数组存在性检查
				const hasEvent = this.resources && Array.isArray(this.resources) && this.resources.some(resource =>
					resource && resource.slots && Array.isArray(resource.slots) && resource.slots.some(slot => slot &&
						slot.date === dateStr)
				);
				return {
					hasEvent: hasEvent,
					isImportant: false
				};
			},



			// 切换月份
			changeMonth(e) {
				const date = new Date(e.detail.value)
				this.currentDate = date
				this.currentMonth = `${date.getFullYear()}年${date.getMonth()+1}月`
				this.initCalendar()
			},

			// 上个月
			prevMonth() {
				this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() - 1, 1)
				this.currentMonth = `${this.currentDate.getFullYear()}年${this.currentDate.getMonth()+1}月`
				this.initCalendar()
			},

			// 下个月
			nextMonth() {
				this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() + 1, 1)
				this.currentMonth = `${this.currentDate.getFullYear()}年${this.currentDate.getMonth()+1}月`
				this.initCalendar()
			},

			// 选择日期
			selectDate(date) {
				this.selectedDate = date
				// 更新日历选中状态
				this.calendarDays.forEach(day => {
					day.isSelected = day.date === date
				})
				// 获取选中日期的团信息
				this.fetchTourGroupByDate(date);
			},

			// 格式化日期显示
			formatDate(dateStr) {
				if (!dateStr) return '';
				// 将YYYY-MM-DD格式转换为MM月DD日
				const parts = dateStr.split('-');
				if (parts.length === 3) {
					return `${parts[1]}月${parts[2]}日`;
				}
				return dateStr;
			},

			// 触摸开始事件
			touchStart(e) {
				// 记录触摸起始位置的X坐标
				this.touchStartX = e.touches[0].clientX;
				// 设置滑动状态为开始
				this.isSwiping = false;
			},

			// 触摸移动事件 - 用于检测是否正在滑动
			touchMove(e) {
				// 如果已经是滑动状态，不再处理
				if (this.isSwiping) return;

				const currentX = e.touches[0].clientX;
				const distance = Math.abs(currentX - this.touchStartX);

				// 当水平移动超过10px时，认为开始滑动
				if (distance > 10) {
					this.isSwiping = true;
				}
			},

			// 触摸结束事件
			touchEnd(e) {
				// 记录触摸结束位置的X坐标
				this.touchEndX = e.changedTouches[0].clientX;
				// 检测滑动并执行相应操作
				this.handleSwipe();
			},

			// 处理滑动逻辑
			handleSwipe() {
				// 定义最小滑动距离，小于这个距离不认为是滑动操作
				const minSwipeDistance = 50;
				// 计算滑动距离
				const swipeDistance = this.touchEndX - this.touchStartX;

				// 向右滑动（显示上个月）
				if (swipeDistance > minSwipeDistance) {
					this.prevMonth();
				}
				// 向左滑动（显示下个月）
				else if (swipeDistance < -minSwipeDistance) {
					this.nextMonth();
				}

				// 重置触摸状态
				this.touchStartX = 0;
				this.touchEndX = 0;
				this.isSwiping = false;
			},

			// 关闭所有抽屉
			closeAllDrawers() {
				this.showGuideDrawer = false;
				this.showVehicleDrawer = false;
			},

			// 根据日期获取团信息
			async fetchTourGroupByDate(date) {
				uni.showLoading({
					title: '加载团信息',
					mask: true
				});

				try {
					// 调用接口获取团信息
					const res = await getTourGroupByDateRange({
						startDate: date + " 00:00:00"
					});

					this.selectedDateGroups = res || [];
					this.updateResourcesFromGroups();
				} catch (error) {

					this.updateResourcesFromGroups();
				} finally {
					uni.hideLoading();
				}
			},

			// 根据团信息更新日历
			updateResourcesFromGroups() {
				// 更新日历
				this.initCalendar();
			},







		}
	}
</script>

<style lang="scss" scoped>
	// 抽屉样式
	.drawer {
		position: fixed;
		left: 0;
		right: 0;
		bottom: -100%;
		max-height: 80%;
		width: 100%;
		background-color: #fff;
		z-index: 9999;
		transition: bottom 0.3s ease;
		box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
		display: flex;
		flex-direction: column;
	}

	.drawer.show {
		bottom: 0;
	}

	.drawer-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16px;
		border-bottom: 1px solid #eee;
	}

	.drawer-title {
		font-size: 18px;
		font-weight: 600;
		color: #333;
	}

	.drawer-close {
		width: 24px;
		height: 24px;
		padding: 4px;
	}

	.drawer-search {
		padding: 16px;
		border-bottom: 1px solid #eee;
	}

	.search-input {
		width: 100%;
		height: 36px;
		border: 1px solid #ddd;
		border-radius: 18px;
		padding: 0 16px;
		font-size: 14px;
	}

	.drawer-body {
		flex: 1;
		overflow-y: auto;
		padding: 8px;
	}

	.drawer-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 12px;
		border-bottom: 1px solid #f5f5f5;
	}

	.drawer-item.active {
		background-color: #f0f8ff;
	}

	.item-selected {
		width: 20px;
		height: 20px;
	}

	.loading-state,
	.no-result {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 32px;
		color: #999;
	}

	// 车辆项特殊样式
	.vehicle-item {
		flex-direction: column;
		align-items: stretch;
	}

	.vehicle-content {
		width: 100%;
	}

	.vehicle-main-info {
		margin-bottom: 8px;
	}

	.vehicle-title {
		font-size: 16px;
		font-weight: 500;
		color: #333;
	}

	.vehicle-info-details {
		margin-top: 8px;
	}

	.vehicle-detail-item {
		display: block;
		font-size: 14px;
		margin-bottom: 4px;
		color: #666;
	}

	.detail-label {
		color: #999;
		margin-right: 4px;
	}

	// 抽屉遮罩层样式
	.drawer-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.3);
		z-index: 9998;
		opacity: 0;
		transition: opacity 0.3s ease;
		pointer-events: none;
	}

	.drawer-mask.show {
		opacity: 1;
		pointer-events: auto;
	}

	.flat-mask {
		background-color: rgba(0, 0, 0, 0.3);
	}

	.detail-value {
		color: #666;
	}

	// 编辑按钮样式
	.edit-btn {
		font-size: 14px;
		color: #007aff;
		background-color: transparent;
		padding: 4px 12px;
		border-radius: 12px;
		border: 1px solid #007aff;
		line-height: 1.8;
	}

	// action-btn 样式（如果使用的是text而非button）
	.action-btn {
		font-size: 14px;
		color: #007aff;
		padding: 4px 12px;
		border-radius: 12px;
		background-color: #e3f2fd;
	}

	// 修复团信息行的样式对齐
	.group-info-row {
		display: flex;
		align-items: center;
		padding: 8px 0;
		justify-content: space-between;
	}

	.info-label {
		font-size: 14px;
		color: #666;
		min-width: 60px;
	}

	.replace-icon {
		display: inline-block;
		width: 14px;
		height: 14px;
		vertical-align: middle;
		margin-left: 4px;
		cursor: pointer;
	}

	.info-value {
		font-size: 14px;
		color: #333;
		flex: 1;
		margin: 0 8px;
	}

	.unassigned {
		border: 1px dashed #ddd;
		background-color: #fafafa;
	}

	.info-container {
		min-height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 8rpx;
	}

	.empty-placeholder {
		width: 100%;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.plus-sign {
		font-size: 36rpx;
		color: #999;
	}

	.resource-calendar {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	/* 团信息展示模块样式 */
	.group-info-container {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-top: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.group-info-header {
		padding-bottom: 15rpx;
		border-bottom: 1px solid #f0f0f0;
		margin-bottom: 15rpx;
	}

	.group-info-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
	}

	.group-list {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}

	.group-item {
		background-color: #fafafa;
		border-radius: 8rpx;
		padding: 15rpx;
	}

	.group-item-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 10rpx;
	}

	.group-name {
		font-size: 26rpx;
		font-weight: 600;
	}

	.group-item-body {
		margin-top: 10rpx;
	}

	/* 横向布局样式 */
	.horizontal-layout {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
	}

	.group-info-item {
		display: flex;
		flex-direction: column;
		flex: 1;
		min-width: 180rpx;

		padding: 10rpx;
		background-color: #f8f8f8;
		border-radius: 8rpx;
		justify-content: space-between;
	}

	.group-info-item.full-width {
		flex: 1 1 100%;
		max-width: none;
	}

	.group-info-row {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
		justify-content: space-between;
	}

	.info-label {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 5rpx;
	}

	.info-value {
		font-size: 26rpx;
		color: #333;
		word-break: break-all;
		margin-bottom: 8rpx;
	}

	.empty-value {
		color: #999;
	}

	.edit-btn {
		font-size: 22rpx;
		background-color: #07c160;
		color: #fff;
		padding: 4rpx 12rpx;
		border-radius: 14rpx;
		align-self: flex-start;
	}

	.empty-group {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 40rpx;
	}

	.empty-text {
		font-size: 24rpx;
		color: #999;
	}

	/* 帮助弹窗样式 */
	.help-modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 9999;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.help-modal-overlay {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.help-modal-content {
		position: relative;
		width: 80%;
		max-width: 600rpx;
		background-color: #fff;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.help-modal-header {
		padding: 30rpx;
		text-align: center;
		border-bottom: 1px solid #f0f0f0;
	}

	.help-modal-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.help-modal-body {
		padding: 30rpx;
		max-height: 500rpx;
		overflow-y: auto;
	}

	.help-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		gap: 20rpx;
	}

	.help-icon {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		flex-shrink: 0;
	}

	.help-icon.blue-bg {
		background-color: #e3f2fd;
	}

	.help-icon.red-bg {
		background-color: #ffebee;
	}

	.help-icon image {
		width: 36rpx;
		height: 36rpx;
	}

	.help-text {
		flex: 1;
	}

	.help-title {
		display: block;
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 8rpx;
	}

	.help-desc {
		display: block;
		font-size: 24rpx;
		color: #666;
		line-height: 1.5;
	}

	.help-modal-footer {
		padding: 20rpx 30rpx 30rpx;
		text-align: center;
	}

	.help-confirm-btn {
		width: 100%;
		height: 80rpx;
		background-color: #007AFF;
		color: #fff;
		font-size: 28rpx;
		border-radius: 40rpx;
		border: none;
	}

	.help-confirm-btn:active {
		background-color: #0051d5;
	}

	// 状态样式
	.status-0 {
		color: #909399;
	}

	.status-1 {
		color: #409EFF;
	}

	.status-2 {
		color: #67C23A;
	}

	/* 头部样式 */
	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		gap: 20rpx;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	/* 月份导航样式 */
	.month-navigation {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8rpx;
		background-color: #f0f8ff;
		border-radius: 6rpx;
		padding: 8rpx;
		margin-bottom: 15rpx;
	}

	/* 团信息头部样式 */
	.group-info-header {
		padding-bottom: 15rpx;
		border-bottom: 1px solid #f0f0f0;
		margin-bottom: 15rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	/* 帮助图标样式 */
	.action-icon {
		width: 40rpx;
		height: 40rpx;
		cursor: pointer;
	}

	.nav-btn {
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		background-color: #fff;
		box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
	}

	.nav-btn:active {
		background-color: #f5f5f5;
	}

	.nav-arrow {
		font-size: 30rpx;
		color: #007AFF;
		font-weight: bold;
	}

	.title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.date-picker {
		font-size: 24rpx;
		color: #007AFF;
		padding: 8rpx 15rpx;
		background-color: #f0f8ff;
		border-radius: 6rpx;
	}



	/* 日历容器 */
	.calendar-container {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 15rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	/* 简化版日历样式 */
	.simple-calendar {
		margin-bottom: 20rpx;
	}

	.calendar-header {
		display: flex;
		margin-bottom: 10rpx;
	}

	.weekday {
		flex: 1;
		text-align: center;
		font-size: 24rpx;
		color: #666;
		font-weight: 500;
		padding: 10rpx 0;
	}

	.calendar-body {
		display: flex;
		flex-wrap: wrap;
	}

	.calendar-cell {
		width: 14.28%;
		height: 80rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		position: relative;
		margin-bottom: 5rpx;
	}

	.day-number {
		font-size: 24rpx;
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.calendar-cell.other-month .day-number {
		color: #ccc;
	}

	.calendar-cell.current-day .day-number {
		background-color: #007AFF;
		color: white;
	}

	.calendar-cell.selected-day .day-number {
		background-color: #4CD964;
		color: white;
		font-weight: bold;
	}

	.event-dot {
		position: absolute;
		bottom: 10rpx;
		width: 8rpx;
		height: 8rpx;
		background-color: #FF9500;
		border-radius: 50%;
	}
</style>